##########################################################
#       kegg  enrichment plot                            #
#       data Aug 13, 2019                                #
#       Shawn Wang                                       #
##########################################################
library(ggplot2)
library(dplyr)
library(magrittr)
library(stringr)
options(stringsAsFactors = F)
Args<-commandArgs(T)
## The 1st parameters is the file path
#fp = "~/14.Heterosis/06.WGCNA/01.leaf/01.GO.enrich/"
fp <- Args[1]
print(fp)
####===========step1 import file===================

setwd(fp)
path.raw <- fp

fileNames.raw <- dir(path.raw, pattern = ".xls") 
filePath.raw <- sapply(fileNames.raw, function(x){ 
  paste(path.raw,x,sep='/')})   
data.raw <- lapply(filePath.raw, function(x){
  read.table(x, sep = "\t",header = TRUE,quote = "",stringsAsFactors = FALSE)}) 
## linux shell for file name
name = sub(pattern = ".final.xls",replacement = "",x = fileNames.raw)
####===========step1 data clearising===================
font.size = 12
data.clean <- list()
x <- list()
y <- list()
Gene_Number <- list()
Qvalue <- list()
for (i in c(1:length(name))) {
  data.clean[[i]] = data.frame(id = factor(data.raw[[i]][,1], levels = data.raw[[i]][,1]),
                               ratio = data.raw[[i]][,3]/data.raw[[i]][,4],
                               Gene_Number = data.raw[[i]][,3],
                               Qvalue = data.raw[[i]][,10])
  y <- data.clean[[i]][,1]
  x <- data.clean[[i]][,2]
  Gene_Number <- data.clean[[i]][,3]
  Qvalue <- data.clean[[i]][,4]
  title <- paste(name[i],"GO enrichment result"," ")
  p.base = ggplot(data.clean[[i]], aes(x=x, y=y))+
    geom_point(aes(color = Qvalue, size = Gene_Number))+
    scale_color_continuous(low="red", high="blue", guide=guide_colorbar(reverse=TRUE))+
    scale_size_continuous(range=c(0, 8))+
    labs(y=NULL) +
    ggtitle(title)+
    theme_bw() +
    theme(axis.text.x = element_text(colour = "black",
                                     size = font.size, vjust =1 ),
          axis.text.y = element_text(colour = "black",
                                     size = font.size, hjust =1 ),
          axis.title = element_text(margin=margin(10, 5, 0, 0),
                                    color = "black",size = font.size),
          axis.title.y = element_text(angle=90))+ 
    labs(x = "Gene_Ratio")
  
  ggsave(plot = p.base,
         filename = paste(name[i],".enrichment.bubbleplot.pdf",sep = ""), 
         width = 10, height = 10)
  ggsave(plot = p.base,
         filename = paste(name[i],".enrichment.bubbleplot.svg",sep = ""), 
         width = 10, height = 10)  
  
}
